package br.com.abelha.manager.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

/**
 * @author dalsonsouza
 */

public class DBAdapter {

	private Context mContext;
	private SQLiteDatabase mDb;
	private AbelhaDBHelper mDbHelper;

	public DBAdapter(Context mContext) {
		this.mContext = mContext;
	}
	
	public DBAdapter open() throws SQLException {
		mDbHelper = new AbelhaDBHelper(mContext);
		mDb = mDbHelper.getWritableDatabase();
		return this;
	}

	public void close() {
		mDbHelper.close();
	}
	
	public void beginTransaction() {
		mDb.beginTransaction();
	}
	
	public void setTransactionSuccessful(){
		mDb.setTransactionSuccessful();
	}
	
	public void endTransaction() {
		mDb.endTransaction();
	}

	public long insert(String table, Object[] contents) {
		return mDb.insert(table, null, createContentValues(contents));
	}
	
	public int delete(String table, String whereClause, String[] whereArgs) {
		return mDb.delete(table, whereClause, whereArgs);
	}
	
	public int update(String table, String whereClause, String[] whereArgs, Object[] contents) {
		return mDb.update(table, createContentValues(contents), whereClause, whereArgs);
	}
	
	public Cursor query(String table, String[] columns, String selection,String[] selectionArgs, String groupBy, String orderBy) {
		return mDb.query(table, columns, selection, selectionArgs, groupBy, null, orderBy);
	}
	
	public int truncate(String table){
		return mDb.delete(table, null, null);
	}

	private ContentValues createContentValues(Object...content) {
		// init a ContentValues object
		ContentValues cv = new ContentValues();
		
		int iKey = 0;
		int iValue = 0;
		for (int i = 0; i < content.length; i++) {
			
			if(i != 0) {
				iKey = iKey + 2;
			}
			iValue = iKey+1;
			
			if(iKey > content.length || iValue > content.length) {
				break;
			}
			
			String key = (String)content[iKey];
			Object value = content[iValue];
			
			if(key == null) {
				return cv;
			}
			
			if(value == null) {
				cv.putNull(key);
				continue;
			}
			
			if (value instanceof Integer) {
				cv.put(key, (Integer)value);
			} else if(value instanceof String) {
				cv.put(key, (String)value);
			} else if(value instanceof Long) {
				cv.put(key, (Long)value);
			} else if(value instanceof Boolean) {
				cv.put(key, (Boolean)value);
			} else {
				cv.putNull(key);
			}
		}
		
		return cv;
	}
}
